package com.samsung.sds.test.editors;

import java.util.Arrays;

import org.eclipse.jface.resource.ImageDescriptor;

public class JSFunctionElement extends JSElement {
	protected String arguments;

	/**
	 * 
	 * @param aName
	 * @param argumentString
	 * @param offset
	 * @param length
	 */
	public JSFunctionElement(String aName, String argumentString, int offset, int length) {
		this(aName, argumentString, offset, length, JSScopeType.FUNCTION);
	}

	/**
	 * 
	 * @param aName
	 * @param argumentString
	 * @param offset
	 * @param length
	 * @param scopeType
	 */
	public JSFunctionElement(String aName, String argumentString, int offset, int length, JSScopeType scopeType) {
		super(aName, offset, length);
		arguments = argumentString;
		getScope().setScopeType(scopeType);

		if (scopeType.equals(JSScopeType.FUNCTION) && !"()".equals(arguments)) {
			addArgumentsToScopeVariable();
		}

	}

	private void addArgumentsToScopeVariable() {
		String[] list = arguments.substring(1, arguments.length() - 1).split(",");

		for (String arg : Arrays.asList(list)) {
			JSVariableElement variable = new JSVariableElement(arg.trim(), 0, 0);

			getScope().addVariable(arg.trim(), variable);
		}
	}

	public ImageDescriptor getImageDescriptor(Object object) {
		return JAVASCRIPTImages.ICON_VIEW_FUNCTION;
	}

	/**
	 * Method declared on IWorkbenchAdapter
	 * 
	 * @param o
	 * 
	 * @return
	 */
	public String getLabel(Object o) {
		String firstPart = name;
		if (firstPart.length() <= 0) {
			firstPart = "<anonymous>";
		}

		return firstPart + arguments;
	}

	public int category() {
		return FUNCTION;
	}

	/**
	 * @return
	 */
	public String getArguments() {
		return arguments;
	}

	public void setName(String name) {
		this.name = name;
		getScope().setScopeName(name);
	}

}
